package cn.xclink.kernel.web;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.xclink.common.web.BaseController;
import cn.xclink.common.web.ExecuteResult;
import cn.xclink.common.web.bind.annotation.CurrentUser;
import cn.xclink.kernel.entity.Org;
import cn.xclink.kernel.entity.Role;
import cn.xclink.kernel.entity.User;
import cn.xclink.kernel.entity.UserRole;
import cn.xclink.kernel.service.OrgService;
import cn.xclink.kernel.service.PasswordHelper;
import cn.xclink.kernel.service.RoleService;
import cn.xclink.kernel.service.UserRoleService;
import cn.xclink.kernel.service.UserService;

@Controller
@RequestMapping("system/user")
public class UserController extends BaseController<User> {

	@Autowired
	private UserService userService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PasswordHelper passwordHelper;
	@Autowired
	private UserRoleService userRoleService;

	public static String LEFT_DIVID = "sys_user_left_div";
	public static String RIGHT_DIVID = "sys_user_right_div";

	/**
	 * 增加了@ModelAttribute的方法可以在本controller方法调用前执行,可以存放一些共享变量,如枚举值,或是一些初始化操作
	 */
	@ModelAttribute
	public void init(Model model) {
		model.addAttribute("left_divid", LEFT_DIVID);
		model.addAttribute("right_divid", RIGHT_DIVID);
	}

	@RequiresPermissions("user:view")
	@RequestMapping
	public String index(@CurrentUser User currentUser, Model model,HttpServletRequest request) {
		//List<Org> orgList = orgService.findOrgByUserId(currentUser.getUserId());
		List<Org> orgList = orgService.findAll();
		model.addAttribute("orgList", orgList);

		List<Role> roleList = roleService.findAll();
		model.addAttribute("roleList", roleList);
		return "system/user/index";
	}

	@RequiresPermissions("user:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser User currentUser, User user, Model model,HttpServletRequest request,
			@RequestParam(value="pageNum",required=false) Integer pageNum, 
			@RequestParam(value="pageSize",required=false) Integer pageSize) {

		//		List<Org> orgList = orgService.findOrgByUserIdAndParentIds(currentUser.getUserId(),user.getParentIds());
		//		model.addAttribute("orgMap",orgService.findOrgIdAndName(orgList));
		//		if(orgList.size() == 0){
		//			model.addAttribute("pageInfo", new PageInfo<User>(new ArrayList<User>()));
		//		}else{
		//			user.setOrgIds(orgService.findOrgIds(orgList));
		//			model.addAttribute("pageInfo", userService.findPageInfo(user, pageNum, pageSize));
		//		}
		model.addAttribute("pageInfo", userService.findPageInfo(user, pageNum, pageSize));
		model.addAttribute("user", user);
		return "system/user/list";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createForm(@CurrentUser User currentUser, Model model, HttpServletRequest request) {

		User user = new User();
		model.addAttribute("user", user);
		//当前用户有权限分配的角色
		//List<Role> roleList = roleService.findRoleByUserId(currentUser.getUserId());
		List<Role> roleList = roleService.findAll();
		model.addAttribute("roleList", roleList);

		//当前用户有权限分配的组织
		//List<Org> orgList = orgService.findOrgByUserId(currentUser.getUserId());
		List<Org> orgList = orgService.findAll();
		model.addAttribute("orgList", orgList);
		return "system/user/create";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> create(@CurrentUser User currentUser,User user, Model model, HttpServletRequest request) {
		try {
			if (userService.findUserByAccount(user.getAccount()) != null) {
				return ExecuteResult.jsonReturn(300, "该帐号已经被使用！", false);
			}
			user.setOrgId(1L);
			userService.saveUser(user);
			return ExecuteResult.jsonReturn(200);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, "忘了角色和授权部门了吧！！！",false);
		}
	}

	@RequiresPermissions("user:edit")
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public String editForm(@CurrentUser User currentUser, @PathVariable("id") Long id, Model model) {
		User user = userService.get(id);
		model.addAttribute("user", user);
		Org org = orgService.get(user.getOrgId());
		if (org != null) {
			model.addAttribute("orgName", org.getOrgName());
		}
		//当前用户有权限分配的角色
		//List<Role> roleList = roleService.findRoleByUserId(currentUser.getUserId());
		List<Role> roleList = roleService.findAll();
		//已经分配的组织
		List<Role> accessRoleList = roleService.findRoleByUserId(id);
		model.addAttribute("roleList", roleService.getRoleTree(roleList,accessRoleList));

		//当前用户有权限分配的组织
		//List<Org> orgList = orgService.findOrgByUserId(currentUser.getUserId());
		List<Org> orgList = orgService.findAll();
		//已经分配的组织
		List<Org> accessOrgList = orgService.findOrgByUserId(id);
		if(accessOrgList.size()>0){
			model.addAttribute("orgIds",Arrays.toString(orgService.findOrgIds(accessOrgList)).replace("[", "").replace("]", "").replace(" ", ""));
		}
		model.addAttribute("orgList", orgService.getOrgTree(orgList,accessOrgList));
		return "system/user/edit";
	}

	@RequiresPermissions("user:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> edit(@CurrentUser User currentUser,User user,Model model,HttpServletRequest request) {
		try {
			userService.updateUser(user);
			return ExecuteResult.jsonReturn(200,RIGHT_DIVID);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, e.getMessage(),false);
		}
	}

	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/deleteM", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteM(@CurrentUser User currentUser,HttpServletRequest request) {
		try {
			String	dels=	request.getParameter("dels");
			userService.deleteMany(dels,currentUser.getUserId());
			return ExecuteResult.jsonReturn(200, true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, e.getMessage(),false);
		}
	}

	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(@CurrentUser User currentUser, @PathVariable("id") Long id,HttpServletRequest request) {
		try {
			userService.delete(id);
			return ExecuteResult.jsonReturn(300, false);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, e.getMessage(),false);
		}
	}
	//修改当前用户的密码
	@RequestMapping(value = "/passwd", method = RequestMethod.GET)
	public String passwd(@CurrentUser User currentUser, Model model) {
		return "passwd";
	}


	@RequestMapping(value = "/passwd", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> passwd(@CurrentUser User currentUser,User user,Model model,HttpServletRequest request) {
		try {

			String passwd = currentUser.getPassword();
			String salt = currentUser.getSalt();
			String oldPasswd = new SimpleHash(
					"md5",
					user.getPassword(),
					ByteSource.Util.bytes(currentUser.getCredentialsSalt()),
					2).toHex();

			if(!passwd.equals(oldPasswd)){
				return ExecuteResult.jsonReturn(300, "请输入正确的原始密码！",false);
			}

			String newpasswd = request.getParameter("newpasswd");
			String confirmpasswd = request.getParameter("confirmpasswd");
			if(!newpasswd.equals(confirmpasswd)){
				return ExecuteResult.jsonReturn(300, "两次输入密码不一致！",false);
			}
			currentUser.setPassword(newpasswd);
			passwordHelper.encryptPassword(currentUser);
			userService.updateNotNull(currentUser);
			return ExecuteResult.jsonReturn(200,RIGHT_DIVID);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, e.getMessage(),false);
		}
	}


	//管理员修改密码
	@RequiresPermissions("user:pwd")
	@RequestMapping(value = "/{id}/pwd", method = RequestMethod.GET)
	public String editpaswd(@CurrentUser User currentUser,@PathVariable("id") Long id,Model model,HttpServletRequest request) {
		model.addAttribute("id",id);
		return "system/user/pwd";
	}


	@RequiresPermissions("user:pwd")
	@RequestMapping(value = "/pwd", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> editpwd(@CurrentUser User currentUser,Model model,HttpServletRequest request) {
		//判断当前身份 如果是普通管理员修改普通管理员密码则不可以


		try {
			String id=	request.getParameter("id");
			String newpasswd=request.getParameter("newpasswd");
			String confirmpasswd =request.getParameter("confirmpasswd");
			if(!confirmpasswd.equals(newpasswd)){
				return ExecuteResult.jsonReturn(300, "两次密码不一致",false);
			}

			User user =userService.getMapper().selectByPrimaryKey(Long.parseLong(id));
//			//查被修改用户的身份
//			UserRole userRole =new UserRole();
//			userRole.setUserId(Long.parseLong(id));
//			UserRole role =userRoleService.findOne(userRole);
//			Long del=role.getRoleId();
//			//如果是普管
//			
//			List<UserRole> roles =userRoleService.find(userRole);
//			if (del==2) {
//				for (UserRole userRole2 : roles) {
//					if(userRole2.getRoleId()==1 || userRole2.getRoleId()==2){
//						return ExecuteResult.jsonReturn(300, "无权限修改其他管理密码",false);
//					}
//				}
//			}

			user.setPassword(newpasswd);
			passwordHelper.encryptPassword(user);
			userService.updateNotNull(user);
			return ExecuteResult.jsonReturn(200,RIGHT_DIVID);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return ExecuteResult.jsonReturn(300, e.getMessage(),false);
		}
	}
}
